<template>
  <TreeSearchPicker
    :key="nodeId"
    :title="title"
    :visible="visible"
    :multiple="multiple"
    :destroy-on-close="destroyOnClose"
    :disabled-keys="disabledKeys"
    :value="preSelectedUsers"
    :lazy="false"
    :searchable="searchable"
    node-key="key"
    :data="treeData"
    :default-props="defaultProps"
    @update:visible="val => close(val)"
    @confirm="onConfirm" />
</template>

<script>
  import TreeSearchPicker from '@/components/TreeSearchPicker'
  import { treeToArray } from '@web-utils/core'
  import { cloneDeep } from '@web-utils/integrations/lodash'
  import { fetchTree } from '@/api/admin/dept'

  export default {
    name: 'UserPicker',
    components: {
      TreeSearchPicker
    },
    props: {
      visible: Boolean,
      multiple: Boolean,
      destroyOnClose: Boolean,
      searchable: {
        type: Boolean,
        default: true
      },
      nodeId: {
        type: [Number, String],
        default: -1
      },
      preSelectedUsers: {
        type: Array,
        default: () => []
      },
      beforeConfirm: Function,
      title: {
        type: String,
        default: '选择用户'
      },
      disabledIds: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        treeData: [],
        defaultProps: {
          label: data => {
            return data.name
          },
          isLeaf: data => {
            return !data.children?.length
          },
          disabled: data => {
            return this.disabledKeys.includes(data.key) || data.type !== 'user'
          }
        }
      }
    },
    computed: {
      disabledKeys() {
        return this.disabledIds.map(value => `user_${value}`)
      }
    },
    created() {
      this.loadNode()
    },
    methods: {
      async loadNode() {
        const res = await fetchTree({ attachUser: true })
        treeToArray(res.data.data).forEach(value => {
          value.key = `${value.type}_${value.id}`
        })
        this.treeData = res.data.data
      },
      onCancel() {
        this.$emit('cancel')
        this.close()
      },
      close() {
        this.$emit('update:visible', false)
      },
      onConfirm(uu) {
        const users = cloneDeep(uu)
        if (this.beforeConfirm) {
          if (this.beforeConfirm(users)) {
            this.$emit('confirm', users)
            this.close()
          }
        } else {
          this.$emit('confirm', users)
          this.close()
        }
      }
    }
  }
</script>
